package jsonTest;


import java.io.IOException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;

import json.Json_City;
import json.Json_Account;
import json.Json_Company;
import json.Json_ManageModel;
import json.Json_Product;
import json.Json_Result;
import json.Json_Verify;
import jsonParser.AccountParser;
import jsonParser.CityParser;
import jsonParser.CompanyParser;
import jsonParser.ProductParser;
import jsonParser.ResultParser;

import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import util.LogUtil;
import util._Config;


import com.google.gson.Gson;
import com.ruiyi.baseparser.Group;
import com.ruiyi.baseparser.GroupParser;
import com.ruiyi.baseparser.Parser;
import com.ruiyi.baseparser.RuiyiType;
import com.ruiyi.error.RuiyiCredentialsException;
import com.ruiyi.error.RuiyiError;
import com.ruiyi.error.RuiyiException;
import com.ruiyi.error.RuiyiParseException;
import com.ruiyi.http.AbstractHttpApi;
import com.ruiyi.http.HttpApi;
import com.ruiyi.http.HttpApiWithBasicAuth;

public class JsonUtil {
	private static final String TAG = "JsonUtil\t";

	private static final String mApiBaseUrl= _Config.URL;
    
	private static final String ENCODE_FORMAT = "UTF-8";

    private static final String URL_API_CITIES = "city.action?act=getlist&id=";
    private static final String URL_API_CITY = "city.action?act=getmodel&id=";
    private static final String URL_API_PRODUCTS = "product?act=getlist&type=company&id=";
    private static final String URL_API_LOGIN = "/member.action?act=login";
	private static final String URL_API_GETMYCOMPANY = "manage.action?module=company&act=getmodel";
	
    private final static DefaultHttpClient mHttpClient = AbstractHttpApi.createHttpClient(); 
    
	public JsonUtil(){
        mHttpApi = new HttpApiWithBasicAuth(mHttpClient, "1.1");        
	}	
    private HttpApi mHttpApi;
    
    /**
     * Takes a parser, a json string, and returns a foursquare type.
     */
    public static RuiyiType consume(Parser<? extends RuiyiType> parser, String content)
        throws RuiyiCredentialsException, RuiyiParseException, RuiyiException, IOException {
        
        try {
        	LogUtil.e(TAG, "http response: " + content);
        	if(content.charAt(0) == '['){
        		LogUtil.e(TAG, "parse array");
            	JSONArray array = new JSONArray(content);            	
            	return parser.parse(array);
        	}
        	else{
        		LogUtil.e(TAG, "parse object");
            	JSONObject obj = new JSONObject(content);            	
            	return parser.parse(obj);       		
        	}
        } catch (JSONException ex) {
            throw new RuiyiException("Error parsing JSON response: " + ex.getMessage());
        }
    }
    private String fullUrl(String url) {
        return mApiBaseUrl + url;    }
    
    @SuppressWarnings("unchecked")
    Group<Json_City> cities(long cities_id) throws RuiyiException, RuiyiCredentialsException,
            RuiyiError, IOException {
    	HttpPost httpGet = mHttpApi.createHttpPost(fullUrl(URL_API_CITIES + cities_id));
        return (Group<Json_City>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CityParser()));
    }
    
    Json_City city(long city_id) throws RuiyiException, RuiyiCredentialsException,
            RuiyiError, IOException {
        HttpPost httpGet = mHttpApi.createHttpPost(fullUrl(URL_API_CITY + city_id));
        return (Json_City) mHttpApi.doHttpRequest(httpGet, new CityParser());
    }
	@SuppressWarnings("unchecked")
	Group<Json_Product> getProductList(long id) throws RuiyiCredentialsException, RuiyiParseException, RuiyiException, IOException {
		HttpPost httpGet = mHttpApi.createHttpPost(fullUrl(URL_API_PRODUCTS + id));
        return (Group<Json_Product>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new ProductParser()));
	}
    
    public Object login(String name, String pswd) throws RuiyiException, RuiyiCredentialsException,
    		RuiyiError, IOException, JSONException {

    	String key = "subgson";
		String sss = getLoginModel(name, pswd);
		NameValuePair m  = new BasicNameValuePair(key,sss);
		
		String json =   mHttpApi.doHttpPost(fullUrl(URL_API_LOGIN), m);
		LogUtil.d(TAG, json);

		JSONObject obj = new JSONObject(json);

		Json_Account ac = new AccountParser().parse(obj);
		if(ac!=null)
			return ac;

		Json_Result result = new ResultParser().parse(obj);
		LogUtil.d(TAG, result.getMessage());
		
		return result;		
    }
    public Object getMyCompany(Json_Account ac) throws RuiyiException, RuiyiCredentialsException,
            RuiyiError, IOException, JSONException {

		LogUtil.d(TAG, "getMyCompany");
		
    	String key = "subgson";
		String sss = preparbox(ac, null);

		NameValuePair m  = new BasicNameValuePair(key,sss);
		
		String json =   mHttpApi.doHttpPost(fullUrl(URL_API_GETMYCOMPANY), m);
		LogUtil.d(TAG, json);

//		Json_Company company = new Gson().fromJson(json, Json_Company.class);
//		if(company.getCompanyName()!=null)
//			return company;	
//		
//		return null;
		
		JSONObject obj = new JSONObject(json);

		Json_Company company = new CompanyParser().parse(obj);
		if(company!=null)
			return company;
		
		Json_Result result = new ResultParser().parse(obj);
		LogUtil.d(TAG, result.getMessage());
		
		return result;	
    }
	//*********************************************************************************************
	public static String getLoginModel(String loginname, String password) {
		Json_ManageModel m = new Json_ManageModel();
		
		m.getAccount().setLoginname(loginname);
		m.getAccount().setPassword(password);

		long l = System.currentTimeMillis();			
		SimpleDateFormat sdf = new SimpleDateFormat("",Locale.SIMPLIFIED_CHINESE); 
		
		sdf.applyPattern("yyyy-MM-dd"); 			
		String timeStr = sdf.format(l); 
		
		System.out.println(timeStr);			
		m.getVerify().setTime(timeStr);
		
		Gson gx = new Gson();
		String sss = gx.toJson(m);

		LogUtil.e(TAG, sss);
		return sss;
	}

	/**
	 * 封装json包
	 * 
	 * @author 刘施洁
	 * @2012-1-6上午08:58:44
	 * @param a
	 * @param s
	 * @return
	 */
	//*********************************************************************************************
	public static String preparbox(Json_Account account, String arg_model) {
//		LogUtil.d(TAG,  "最后:"+new Gson().toJson(ac));
		try{			
			Json_ManageModel model = new Json_ManageModel();
			
			model.setAccount(account);
			model.setModel(arg_model);
	
			Json_Verify verify = new Json_Verify();
			verify.setTime(new Date().toString());
			verify.setPermit("123");// 设置定义好的干扰字符
	
			model.setVerify(verify);
			
			
			JSONStringer jsonText = new JSONStringer();
			jsonText.object(); 
			
		    jsonText.key("name");   
		    jsonText.value("yuanzhifei89");  
		    
		    LogUtil.e(TAG, "jsonText.toString():"+jsonText.toString());
		    
			String tmpstr = new Gson().toJson(model);
			model.getVerify().setPermit(MD5(tmpstr));// 使用md5加密后替换原来的干扰字符
	
			String str = new Gson().toJson(model);// 加入json
			return str;
		} catch (Exception e){
			e.printStackTrace();
			return "";
		}
	}

	//*********************************************************************************************
	/**
	 * MD5加密
	 * 
	 * @author 刘施洁
	 * @2012-1-6上午09:02:37
	 * @param sStr
	 * @return
	 */
	public static String MD5(String sStr) {
		String sReturnCode = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(sStr.getBytes(ENCODE_FORMAT));
			byte b[] = md.digest();
			int i;
			StringBuffer sb = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0) {
					i += 256;
				}
				if (i < 16) {
					sb.append("0");
				}
				sb.append(Integer.toHexString(i));
			}

			sReturnCode = sb.toString();
		} catch (Exception ex) {

		}
		return sReturnCode;
	}
}